package com.nanjia.boot.delivery.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanjia.boot.common.enums.StatusEnum;
import com.nanjia.boot.core.security.util.SecurityUtils;
import com.nanjia.boot.delivery.converter.CertificateConverter;
import com.nanjia.boot.delivery.mapper.CertificateMapper;
import com.nanjia.boot.delivery.model.entity.Certificate;
import com.nanjia.boot.delivery.model.form.CertificateForm;
import com.nanjia.boot.delivery.model.query.CertificateQuery;
import com.nanjia.boot.delivery.model.vo.CertificateVO;
import com.nanjia.boot.delivery.service.CertificateService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 证件服务实现类
 *
 * @author 周洋
 * @since 2025-06-13 11:09
 */
@Service
@RequiredArgsConstructor
public class CertificateServiceImpl extends ServiceImpl<CertificateMapper, Certificate> implements CertificateService {

    private final CertificateConverter certificateConverter;

    /**
    * 获取证件分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<CertificateVO>} 证件分页列表
    */
    @Override
    public IPage<CertificateVO> getCertificatePage(CertificateQuery queryParams) {
        queryParams.setSubdomainCode(SecurityUtils.getSubdomainCode());
        queryParams.setSubdomainUserCode(SecurityUtils.getUserCode());
        Page<CertificateVO> pageVO = this.baseMapper.getCertificatePage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取证件表单数据
     *
     * @param id 证件ID
     * @return 证件表单数据
     */
    @Override
    public CertificateForm getCertificateFormData(Long id) {
        Certificate entity = this.getById(id);
        return certificateConverter.toForm(entity);
    }
    
    /**
     * 新增证件
     *
     * @param formData 证件表单对象
     * @param ipAddr
     * @return 是否新增成功
     */
    @Override
    public boolean saveCertificate(CertificateForm formData, String ipAddr) {
        LambdaQueryWrapper<Certificate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Certificate::getId);
        List<Certificate> list = this.list(queryWrapper);
        int x = 0;
        if (CollectionUtils.isNotEmpty(list)) {
            x = Integer.parseInt(list.get(0).getCertificateCode());
        }

        Certificate entity = certificateConverter.toEntity(formData);
        entity.setSubdomainUserCode(SecurityUtils.getUserCode());
        entity.setSubdomainCode(SecurityUtils.getSubdomainCode());
        entity.setCertificateCode(String.format("%04d", x + 1));
        entity.setCreateBy(SecurityUtils.getUserStrId());
        entity.setCreateIp(ipAddr);
        entity.setCreateTime(LocalDateTime.now());
        entity.setCertificateStatus(StatusEnum.ENABLE.getValue());
        return this.save(entity);
    }
    
    /**
     * 更新证件
     *
     * @param id   证件ID
     * @param formData 证件表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateCertificate(Long id,CertificateForm formData) {
        Certificate entity = certificateConverter.toEntity(formData);
        entity.setId(id);
        return this.updateById(entity);
    }
    
    /**
     * 删除证件
     *
     * @param ids 证件ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCertificates(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的证件数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        List<Certificate> list = new ArrayList<>();
        for (Long l : idList) {
            Certificate certificate = new Certificate();
            certificate.setId(l);
            certificate.setUpdateTime(LocalDateTime.now());
            certificate.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
            certificate.setCertificateStatus(StatusEnum.DELETE.getValue());
            list.add(certificate);
        }
        return this.updateBatchById(list,idList.size());
    }

}
